package com.experiment.experiment_big.controller;


import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.experiment.experiment_big.entity.DangerRegion;
import com.experiment.experiment_big.entity.EpidmicData;
import com.experiment.experiment_big.entity.vo.User_Multiple;
import com.experiment.experiment_big.entity.vo.User_Vo;
import com.experiment.experiment_big.service.DangerRegionService;
import com.experiment.experiment_big.service.EpidmicDataService;
import com.experiment.experiment_big.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author testjava
 * @since 2021-06-13
 */
@Controller
@Slf4j
public class UserController {
    @Autowired
    private EpidmicDataService epidmicDataService;

    @Autowired
    private UserService userService;
    @Autowired
    private DangerRegionService dangerRegionService;
    //跳转到登录页面
    @RequestMapping("/tlogin")
    public String login() {
        return "login" ;
    }
    @RequestMapping("/login.html")
    public String relogin() {
        return "login" ;
    }
    //登陆成功
    @RequestMapping("/tindex")
    public String loginsuccess(Model model){

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User principal1 =(User) authentication.getPrincipal();
        String id = principal1.getUsername();
        //查出用户信息
        com.experiment.experiment_big.entity.User byId = userService.getById(id);
        //查询用户人数
        List<com.experiment.experiment_big.entity.User> list = userService.list(null);
        int count = list.size();
        int admin = 0; //管理员人数
        int no_clock = 0;//未打卡
        int alerty_clock = 0; //已打卡
        int tiwen_high = 0;//体温异常用户

        //查询当天体温异常用户
        Date dang = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //获取今天的日期
        String nowDay = sdf.format(dang);
        String startDayTime = nowDay+" 00:00:00"; //2020-08-04 00:00:00
        //加一天
        Calendar cal = Calendar.getInstance();
        Date dzDateObj = null;
        try {
            dzDateObj= sdf.parse(nowDay);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        cal.setTime(dzDateObj);
        cal.add(Calendar.DAY_OF_YEAR,1);
        Date addDate = cal.getTime();
        String endDayTime = sdf.format(addDate)+" 00:00:00";//2020-08-05 00:00:00
        QueryWrapper<EpidmicData> epidmicDataWrapper = new QueryWrapper<>();

        //查询指定字段
        epidmicDataWrapper.select("data_id","user_id","temperature","filling_date","address");

        //查询条件为时间范围
        epidmicDataWrapper.apply("UNIX_TIMESTAMP(filling_date) >= UNIX_TIMESTAMP('"+startDayTime+"')");
        epidmicDataWrapper.apply("UNIX_TIMESTAMP(filling_date) < UNIX_TIMESTAMP('"+endDayTime+"')");
        //查询当天所有
        epidmicDataWrapper.ge("temperature",37.3);
        List<EpidmicData> epidmicData = epidmicDataService.list(epidmicDataWrapper);
        tiwen_high = epidmicData.size();



        //遍历用户
        for(com.experiment.experiment_big.entity.User a : list){
            SimpleDateFormat af = new SimpleDateFormat("yyyy-MM-dd");

            //获得last_punch_time
            Date last_punch_time = a.getLastPunchTime();
            // 当前时间
            Date now = new Date();
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            //获取今天的日期
            String nowDayq = sf.format(now);
            //对比的时间
            String day = sf.format(last_punch_time);
            LocalDateTime yesterday = LocalDateTime.of( LocalDate.now() , LocalTime.MIN ).plusDays( -1 ) ;
            String yesterdayStr = yesterday.toLocalDate().toString() ;
            if(nowDayq.equals(day)){
                //隐藏提交按钮
                if(a.getUserId().equals(byId.getUserId())){
                    model.addAttribute("if_clo",false);
                }
                //今天已提交
                alerty_clock++;
            }else if(day.equals(yesterdayStr)){
                //昨天提交过，没中断
                if(a.getUserId().equals(byId.getUserId())){
                    model.addAttribute("if_clo",true);
                }
                //今天未提交
                no_clock++;
            }else{
                //打卡中断
                if(a.getUserId().equals(byId.getUserId())) {
                    byId.setConsecutiveDay(0);
                    userService.updateById(byId);
                    model.addAttribute("if_clo",true);
                }

                no_clock++;
            }
            if(a.getRole().equals("admin")){
                //管理员人数++
                admin++;
            }
        }
        //风险地区数目统计
        List<DangerRegion> listdanger = dangerRegionService.list(null);


        model.addAttribute("user",byId);//用户信息
        if(byId.getRole().equals("admin")){
            int low = 0;//低风险
            int zhong = 0;//中风险
            int high = 0;//高风险

            for(DangerRegion d : listdanger){
                if(d.getDangerLevel()==1){
                    low++;
                }else if(d.getDangerLevel()==2){
                    zhong++;
                }else{
                    high++;
                }
            }
            model.addAttribute("low",low);//低风险
            model.addAttribute("zhong",zhong);//中风险
            model.addAttribute("high",high);//高风险
            model.addAttribute("count",count);//用户人数
            model.addAttribute("admin",admin);//管理员输入
            model.addAttribute("users",count-admin);//普通用户
            model.addAttribute("alerty_clock",alerty_clock);//已打卡人数
            model.addAttribute("no_clock",no_clock);//未打卡人数

            model.addAttribute("tiwen_high",tiwen_high);//体温异常用户
            return "index";
        }else{
            List<DangerRegion> dangerRegionList = new ArrayList<>();
            dangerRegionList = dangerRegionService.list(null);
            List<DangerRegion> highdangerRegionList = new ArrayList<>();
            List<DangerRegion> zhongdangerRegionList = new ArrayList<>();
            for(DangerRegion dangerRegion:dangerRegionList){
                if(dangerRegion.getDangerLevel()==2){
                    zhongdangerRegionList.add(dangerRegion);
                }else if(dangerRegion.getDangerLevel()==3){
                    highdangerRegionList.add(dangerRegion);
                }
            }

            model.addAttribute("high",highdangerRegionList);
            model.addAttribute("zhong",zhongdangerRegionList);
            return "submit_form";
        }

    }
    //用户名或密码错误
    @RequestMapping("/loginerror")
    public String loginerror(Model model){
        model.addAttribute("msg","用户名或密码错误");
        return "login";
    }
    //跳转到注册页面
    @RequestMapping("/register")
    public String register(){
        return "register";
    }

    //用户注册
    @PostMapping("/form/register")
    public String formregister(com.experiment.experiment_big.entity.User user){
        String password = user.getPassword();
        //密码加密
        BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        //加密
        String newPassword = passwordEncoder.encode(password);
        user.setRole("user");
        user.setPassword(newPassword);
        Date date = new Date(0L);
        user.setLastPunchTime(date);
        user.setConsecutiveDay(0);
        boolean fate = true;
        try {
            fate = userService.save(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(fate){
            return "login";
        }else{
            return "register";
        }
    }

    //删除用户
    @RequestMapping("/deleteUser")
    public String deleteUser(String id){
        System.out.println(id);
        userService.removeById(id);
        return "redirect:/allUser";
    }
    //多条件查询
    @RequestMapping("/user_multiple")
    public String user_multiple(User_Multiple user_multiple,Model model){



        QueryWrapper<com.experiment.experiment_big.entity.User> userQueryWrapper = new QueryWrapper<>();
        //姓名模糊查询
        if(!user_multiple.getUser_name().equals("")){
            userQueryWrapper.like("user_name",user_multiple.getUser_name());
        }
        //连续打卡
        if(user_multiple.getConsecutive_day()!=null){
            userQueryWrapper.ge("consecutive_day",user_multiple.getConsecutive_day());
        }
        //用户角色查询
        if(!user_multiple.getRole().equals("")){
            userQueryWrapper.eq("role",user_multiple.getRole());
        }
        List<com.experiment.experiment_big.entity.User> list = userService.list(userQueryWrapper);


        List<User_Vo> user_vos = new ArrayList<>();
        for(com.experiment.experiment_big.entity.User user : list){
            User_Vo user_vo = new User_Vo();
            user_vo.setUserId(user.getUserId());
            user_vo.setIdCode(user.getIdCode());
            user_vo.setNativePlace(user.getNativePlace());
            user_vo.setPhone(user.getPhone());
            user_vo.setUserName(user.getUserName());
            user_vo.setRole(user.getRole());
            user_vo.setConsecutiveDay(user.getConsecutiveDay());
            //获得last_punch_time
            Date last_punch_time = user.getLastPunchTime();
            // 当前时间
            Date now = new Date();
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            //获取今天的日期
            String nowDay = sf.format(now);
            //对比的时间
            String day = sf.format(last_punch_time);

            if(nowDay.equals(day)){
                //今天已提交
                user_vo.setIf_clock("已打卡");
            }else{
                //今天未提交
                user_vo.setIf_clock("未打卡");
            }
            user_vos.add(user_vo);
        }

        model.addAttribute("users",user_vos);
        return "Multiple_conditions";

    }


    /**
     * 查询所有用户
     * @param model
     * @return
     */
    @RequestMapping("/allUser")
    public String tAllUser(Model model, String excel,HttpServletResponse response) throws IOException {
        //查询所有用户
        List<com.experiment.experiment_big.entity.User> list = userService.list(null);
        List<User_Vo> user_vos = new ArrayList<>();

        for(com.experiment.experiment_big.entity.User user : list){
            User_Vo user_vo = new User_Vo();
            user_vo.setUserId(user.getUserId());
            user_vo.setIdCode(user.getIdCode());
            user_vo.setNativePlace(user.getNativePlace());
            user_vo.setPhone(user.getPhone());
            user_vo.setUserName(user.getUserName());
            user_vo.setRole(user.getRole());
            user_vo.setConsecutiveDay(user.getConsecutiveDay());
            //获得last_punch_time
            Date last_punch_time = user.getLastPunchTime();
            // 当前时间
            Date now = new Date();
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            //获取今天的日期
            String nowDay = sf.format(now);
            //对比的时间
            String day = sf.format(last_punch_time);

            if(nowDay.equals(day)){
                //今天已提交
                user_vo.setIf_clock("已打卡");
            }else{
                //今天未提交
                user_vo.setIf_clock("未打卡");
            }
            user_vos.add(user_vo);
        }
        if(excel!=null){
            ServletOutputStream out = out = response.getOutputStream();
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
            String filename = "所有用户";
            writer.write(user_vos,new WriteSheet());

            //通知浏览器以附件的形式下载处理，设置返回头要注意文件名有中文
            response.setHeader("Content-disposition", "attachment;filename=" + new String( filename.getBytes("gb2312"), "ISO8859-1" ) + ".xlsx");
            writer.finish();
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            out.flush();
        }
        model.addAttribute("users",user_vos);
        return "alluser";
    }
    /**
     * 跳转到多条件查询用户
     * @param model
     * @return
     */
    @RequestMapping("/multiple_conditions")
    public String multiple_conditions(Model model){
        List<com.experiment.experiment_big.entity.User> list = userService.list(null);
        List<User_Vo> user_vos = new ArrayList<>();

        for(com.experiment.experiment_big.entity.User user : list){
            User_Vo user_vo = new User_Vo();
            user_vo.setUserId(user.getUserId());
            user_vo.setIdCode(user.getIdCode());
            user_vo.setNativePlace(user.getNativePlace());
            user_vo.setPhone(user.getPhone());
            user_vo.setUserName(user.getUserName());
            user_vo.setRole(user.getRole());
            user_vo.setConsecutiveDay(user.getConsecutiveDay());
            //获得last_punch_time
            Date last_punch_time = user.getLastPunchTime();
            // 当前时间
            Date now = new Date();
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            //获取今天的日期
            String nowDay = sf.format(now);
            //对比的时间
            String day = sf.format(last_punch_time);

            if(nowDay.equals(day)){
                //今天已提交
                user_vo.setIf_clock("已打卡");
            }else{
                //今天未提交
                user_vo.setIf_clock("未打卡");
            }
            user_vos.add(user_vo);
        }
        model.addAttribute("users",user_vos);
        return "Multiple_conditions";
    }
}

